import { useMemoizedFn } from 'ahooks';
import { Cartesian3, ImageryLayer, UrlTemplateImageryProvider } from 'cesium';
import { isNil } from 'lodash';
import { useEffect } from 'react';
import { useCesium } from 'resium';
import { useAppSelector } from '../../../../store';

export default function Demo() {
    const { viewer } = useCesium();
    const pos = useAppSelector((state) => state.scene.initPosition);

    const clearImageryLayers = useMemoizedFn(() => {
        if (isNil(viewer)) return;
        if (viewer.imageryLayers.get(0)) {
            viewer.imageryLayers.remove(viewer.imageryLayers.get(0));
            clearImageryLayers();
        } else {
            return;
        }
    });

    useEffect(() => {
        if (isNil(viewer)) return;
        clearImageryLayers();

        const url = 'http://gac-geo.googlecnapps.cn/maps/vt?lyrs=s&x={x}&y={y}&z={z}';
        const layer = new ImageryLayer(
            new UrlTemplateImageryProvider({
                url,
            })
        );
        viewer.imageryLayers.add(layer);

        const target = Cartesian3.fromDegrees(pos.longitude, pos.latitude, 10000000);
        viewer.camera.setView({
            destination: target,
        });
    }, [clearImageryLayers, pos, viewer]);

    return null;
}
